#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GuizhouHpxrmzfB9b9Policy(BaseTaxPolicySpider):
    name = 'guizhou_hpxrmzf_b9b9_policy'

    province = '贵州省'
    city = '黔东南苗族侗族自治州'
    county = '黄平县'
    park = ''
    source = '黄平县人民政府'
    url = 'https://www.qdnhp.gov.cn/xxgk/jcgk/zcwj/'
    host_url = url.split('.gov.cn')[0] + '.gov.cn'
    headers = {
        "Content-Type": "application/json;charset=UTF-8",
    }

    def start_requests(self):
        yield self.Request(
            'https://www.qdnhp.gov.cn/xxgk/jcgk/zcwj/index.json',
            callback=self.parse_list,
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['data']:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['PubDate']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.html' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        # data = response.meta.get('data')
        # if response.meta.get("is_next") is not False:
        #     total_page = response.json()['data']['pager']['pageCount']
        #     print("total", response.json()['data']['pager']['total'])
        #     for page_num in range(2, int(total_page) // 1 + 1):
        #         data['pageNo'] = page_num
        #         yield response.follow(response.url, method="POST", headers=self.headers, body=json.dumps(data, separators=(',', ':')),
        #                               callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl guizhou_hpxrmzf_b9b9_policy".split())
